const useSessionStorage = () => {
  const TOKEN_EXPIRE_MINUTES = 30 // 设置过期时间为30分钟

  const remove = (key) => {
    sessionStorage.removeItem(key)
  }

  const set = (key, loginuser) => {
    const params = {
      data: loginuser,
      time: Date.parse(new Date()) + TOKEN_EXPIRE_MINUTES * 60 * 1000 // 30分钟过期
    }
    sessionStorage.setItem(key, JSON.stringify(params))
  }

  const refreshExpiration = (key, data) => {
    set(key, data)
  }

  const get = (key) => {
    const v = sessionStorage.getItem(key)
    if (v && typeof v !== 'undefined' && v !== 'undefined') {
      const params = JSON.parse(v)
      if (params.time) {
        if (params.time > Date.parse(new Date())) {
          // 如果token未过期，刷新过期时间
          refreshExpiration(key, params.data)
          return params.data
        }
        remove(key)
      }
    }
    return null
  }

  const clearAll = () => {
    sessionStorage.clear()
  }

  return {
    get,
    set,
    remove,
    clearAll
  }
}

export default useSessionStorage
